package com.xbai.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.xbai.search.pojo.SkuInfo;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author jxbai
 * @desc 自定义结果集映射 目的: 获取高亮的数据
 * @date 2021/2/1
 */
public class SearchResultMapperImpl implements SearchResultMapper {
    @Override
    public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
        List<T> content = new ArrayList<>();
        //如果没有结果返回为空
        if (searchResponse.getHits() == null || searchResponse.getHits().getTotalHits() <= 0) {
            return new AggregatedPageImpl<>(content);
        }
        for (SearchHit hit : searchResponse.getHits()) {
            String sourceAsString = hit.getSourceAsString();
            SkuInfo skuInfo = JSON.parseObject(sourceAsString, SkuInfo.class);

            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField highlightField = highlightFields.get("name");

            //有高亮则设置高亮的值
            if(highlightField != null) {
                StringBuilder stringBuilder = new StringBuilder();
                for (Text text : highlightField.getFragments()) {
                    stringBuilder.append(text);
                }
                skuInfo.setName(stringBuilder.toString());
            }
            content.add((T) skuInfo);
        }
        return new AggregatedPageImpl<>(content, pageable,
                searchResponse.getHits().getTotalHits(),
                searchResponse.getAggregations(),
                searchResponse.getScrollId());
    }

    @Override
    public <T> T mapSearchHit(SearchHit searchHit, Class<T> aClass) {
        return null;
    }
}
